﻿using Developer.Core.FrameWork.ClusterLoadBalance.Service;
using Developer.Core.FrameWork.DynamicMiddlePlatformService.Service;
using Developer.Core.FrameWork.RegisterCenter.Model;
using Developer.Core.FrameWork.RegisterCenter.Service;
using System;
using System.Collections.Generic;
using System.Text;

namespace Developer.Core.FrameWork.DynamicMiddlePlatformService.Impl
{
    /// <summary>
    /// 动态中台url实现类
    /// </summary>
    public class DefaultDynamicMiddlePlatformUrl : IDynamicMiddlePlatformUrl
    {
        private readonly IServiceDiscovery serviceDiscovery;
        private readonly ILoadBalance loadBalance;
        public DefaultDynamicMiddlePlatformUrl(IServiceDiscovery serviceDiscovery,ILoadBalance loadBalance)
        {
            this.serviceDiscovery = serviceDiscovery;
            this.loadBalance = loadBalance;
        }

        /// <summary>
        /// 获取服务url
        /// </summary>
        /// <param name="urlScheme"></param>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public string GetMiddlePlatformUrl(string urlScheme, string serviceName)
        {
            // 1、获取服务
            List<ServiceNode> listServiceUrl = this.serviceDiscovery.Discovery(serviceName);

            if (listServiceUrl.Count == 0)
                throw new ArgumentNullException($"服务：{serviceName}不存在");

            // 2、负载均衡选择
            ServiceNode serviceNode = this.loadBalance.Select(listServiceUrl, serviceName);

            // 3、构建url
            StringBuilder builder = new StringBuilder();
            builder.Append(urlScheme);
            builder.Append("://");
            builder.Append(serviceNode.ServiceAddress);
            builder.Append(":"+serviceNode.ServicePort);
            return builder.ToString();
        }
    }
}
